package demo.websocket.server.example3;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import demo.websocket.server.example3.po.Msg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.HtmlUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Controller
public class MessageMappingController {

    private static final Logger logger = LoggerFactory.getLogger(MessageMappingController.class);

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/request-without-response")
    public void handleMessageWithoutResponse(String message) {
        logger.info("Message without response: {}", message);
    }

    // response is sent to the endpoint /topic/request-with-implicit-response
    @MessageMapping("/request-with-implicit-response")
    public String handleMessageWithImplicitResponse(String message) {
        logger.info("Message with response: {}", message);
        return "response to " + HtmlUtils.htmlEscape(message);
    }

    @MessageMapping("/request")
//    @SendTo("/topic/periodic")
//    public String handleMessageWithExplicitResponse(Message<?> message) {
    public void handleMessageWithExplicitResponse(Message<?> message) {
        String payload = null;
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        String userId = accessor.getNativeHeader("userId").get(0);
        String toUserId = accessor.getNativeHeader("toUserId").get(0);
        try {
            payload = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("返回消息 userId={},toUserId={},payload={}", userId,toUserId,payload);
//        simpMessagingTemplate.convertAndSend("/topic/periodic", message);
    }

    @GetMapping("/sendMsgByUser")
    public @ResponseBody
    Object sendMsgByUser(String token, String msg) {
        logger.info("sendMsgByUser token={},msg={}", token, msg);
        simpMessagingTemplate.convertAndSendToUser(token, "/msg", msg);
        return "success";
    }

    @GetMapping("/sendMsgByAll")
    public @ResponseBody
    Object sendMsgByAll(String msg) {
        logger.info("sendMsgByAll ,msg={}", msg);
        simpMessagingTemplate.convertAndSend("/topic/periodic", msg);
        return "success";
    }

    @MessageExceptionHandler
//    @SendTo("/queue/responses")
    public String handleException(Throwable exception) {
        logger.error("Server exception", exception);
        return "server exception: " + exception.getMessage();
    }
}
